<?php

/**
 * 开始直播提示推送
 *
 * User: jewens
 */
class Base extends MY_Cron_Controller
{    
    /**
     * 开始直播前5分钟提示
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/before_start
     */
    public function before_start()
    {
    	$start_time = strtotime("+3 minutes");
        $where = array
        (
            'status'       => DS_STATUS_NOT,
            'start_time>=' => date('Y-m-d H:i:00', $start_time),
        	'start_time<=' => date('Y-m-d H:i:59', $start_time),
        );

        $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
        $data = $this->ds->getAllLists($where);
        
        $this->load->model('user/Model_user', 'u');
        
        foreach ($data as $v)
        {
        	$anchor_name = $this->u->getById($v['anchor_uid']);
        	if (empty($anchor_name))
        	{
        		return sur(array(), 10002);
        	}


        	$auction_name = $this->u->getById($v['auction_uid']);
        	if (empty($auction_name))
        	{
        		return sur(array(), 10002);
        	}


        	$replace_content = array
            (
                '#auction_name#' => $auction_name['nickname'],
                '#anchor_name#'  => $anchor_name['nickname'],
                '#title#'        => $v['title'],
            );


        	$attach = array
            (
                'ds_id'       => $v['ds_id'],
                'title'       => $v['title'],
                'anchor_uid'  => $v['anchor_uid'],
                'auction_uid' => $v['auction_uid'],
            );
	        //给主播推送消息
        	$this->load->service('message/service_message_push');
        	$this->service_message_push->start_prefix_direct_seeding_anchor($v['anchor_uid'], $attach, $replace_content);


            //给副主播推送消息
            $this->load->service('message/service_message_push');
            $this->service_message_push->start_prefix_direct_seeding_auction($v['auction_uid'], $attach, $replace_content);
        }
    }
    
    /**
     * 开始直播
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/start_live
     */
    public function start_live()
    {
    	$where = array
    	(
            'status'       => DS_STATUS_DOING,
            'real_start_time >=' => date('Y-m-d H:i:00', TIMESTAMP),
            'real_start_time <=' => date('Y-m-d H:i:59', TIMESTAMP),
    	);
    
    	$this->load->model('direct_seeding/Model_direct_seeding', 'ds');
    	$data = $this->ds->getAllLists($where);
    	
    	$this->load->service('message/service_message_push');
        $this->load->model('user/Model_user', 'u');
    	$this->load->model('user/Model_user_friend', 'uf');
    	
    	foreach ($data as $v)
    	{
    		// 推送
    		if($v['is_public'] == DIRECT_SEEDING_IS_PUBLISH_OPEN)
    		{
    			$friend_uid = $this->uf->getAllLists(array('friend_uid' => $v['anchor_uid']));
    			
    			$anchor_name = $this->u->getById($v['anchor_uid']);
    			if (empty($anchor_name))
    			{
    				return sur(array(), 10002);
    			}
    		
    			$uids = array();
    			foreach($friend_uid as $val)
    			{
    			    if ($val['uid'] == $v['anchor_uid'])
    			        continue;


    				$uids[] = $val['uid'];
    			}
    		
    			if($uids)
    			{
    				$uids = array_chunk($uids, 1000);
    		
    				foreach ($uids as $uids_val)
    				{
    					$this->service_message_push->start_direct_seeding_fans($uids_val, array('ds_id'=>$v['ds_id'], 'title'=>$v['title']), array('#anchor_name#' => $anchor_name['nickname']));
    				}
    			}
    		}
    	}
    }
    

    /**
     * 直播信息
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/live_info
     */
    public function live_info()
    {
    	set_time_limit(0);
    	echo time()."\n";
    	$this->load->service('message/service_message_im');
    	$this->load->model('direct_seeding/Model_direct_seeding', 'ds');
    	$this->load->model('direct_seeding/Model_direct_seeding_join_log', 'dsjl');
    	$this->load->model('user/Model_user', 'u');
    	
    	$for_i = 0;
    	while($for_i < 30)
    	{
            $for_i++;
    	    sleep(2);

	    	$where = array
	    	(
                'status'    => DS_STATUS_DOING,
                'is_public' => DIRECT_SEEDING_IS_PUBLISH_OPEN,
	    	);
	    	
	    	$data = $this->ds->getAllLists($where);

	    	if(!$data)
	    	{
	    		continue;
	    	}
	    	
	    	foreach ($data as $v)
	    	{
	    		$dsjl_number = $this->dsjl->online_number($v['ds_id']);
	    		$dsjl_number = $dsjl_number['data']['number'];


	    		if(!$dsjl_number)
	    		{
	    			continue;
	    		}
	    		
	    		$data = array
                (
                    'chat_room_num' => $v['chat_room_num'],
                    'content' => '@MSMK@LIVE_ONLINE_NUMBER@'.$dsjl_number,
	    		);
	    		$send_rs = $this->service_message_im->group_send($data);
	    		
	    		$contribution_uid = $this->dsjl->contribution($v['ds_id'], 0, 20);
	    		
	    		$uids = array_column($contribution_uid, 'uid');
	    		array_unshift($uids, $v['anchor_uid'], $v['auction_uid']);
	    		
	    		$user_data = $this->u->getByIn('uid', $uids);
	    		
	    		$contribution = array();
	    		foreach($uids as $uid)
	    		{
	    		    if (!$uid)
                        continue;


	    			$contribution[] = array('uid'=>$uid, 'header'=>user_header($user_data[$uid]['header']));
	    		}

	    		
	    		$contribution = json_encode($contribution);
	    		
	    		
	    		$data = array
                (
                    'chat_room_num' => $v['chat_room_num'],
                    'content' => '@MSMK@LIVE_CONTRIBUTION@'.$contribution,
	    		);


	    		$send_rs = $this->service_message_im->group_send($data);
	    	}
    	}


        echo time()."\n";
    }
    


    
    /**
     * 直播迟到  直播开始5分钟后，未开播则推送给主播和副主播
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/live_late
     */
    public function live_late()
    {
    	$start_time = strtotime("-5 minute");
    	$where = array
    	(
    	    'status'       => DS_STATUS_NOT,
            'start_time>=' => date('Y-m-d H:i:00', $start_time),
        	'start_time<=' => date('Y-m-d H:i:59', $start_time),
    	);
    	
    	$this->load->model('user/Model_user', 'u');

    	$this->load->model('direct_seeding/Model_direct_seeding', 'ds');
    	$data = $this->ds->getAllLists($where);


    	foreach ($data as $v)
    	{    		 
    		//推送消息
    		$this->load->service('message/service_message_push');
    		
    	
	        $anchor_name = $this->u->getById($v['anchor_uid']);
	        if (empty($anchor_name))
	        {
	        	return sur(array(), 10002);
	        }
	        
	        $auction_name = $this->u->getById($v['auction_uid']);
	        if (empty($auction_name))
	        {
	        	return sur(array(), 10002);
	        }
    		
    		$end_time = strtotime($v['start_time']) + $v['duration']*60;
    		$late_time = strtotime($v['start_time']) + 300;
    		$replace_content = array
            (
                '#anchor_name#'  => $anchor_name['nickname'],
                '#auction_name#' => $auction_name['nickname'],
                '#title#'        => $v['title'],
                '#late_time#'    => date('m月d日H时i分', $late_time),
                '#end_time#'     => date('m月d日H时i分', $end_time),
            );
    		$attach = array
            (
                'ds_id'       => $v['ds_id'],
                'title'       => $v['title'],
                'anchor_uid'  => $v['anchor_uid'],
                'auction_uid' => $v['auction_uid'],
            );
    		$this->service_message_push->live_late_anchor($v['anchor_uid'], $attach, $replace_content);
    		$this->service_message_push->live_late_auction($v['auction_uid'], $attach, $replace_content);
    	}
    }
    
    
    /**
     * 直播结束im通知
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/live_end_notice
     */
    public function live_end_notice()
    {
        /*
    	$this->load->library('im_api/TimRestApi');
    	 
    	$api = createRestAPI();
    	 
    	$ret = $api->generate_user_sig();
    	if ($ret == null)
    	{
    		// 签名生成失败
    		echo '签名生成失败';
    		die();
    	}
        //*/
    	
    	$now_time = strtotime(date('Y-m-d H:i:00'));
    	$real_end_time = date('Y-m-d H:i:59', strtotime("+5 minute"));
    	
    	$where = array
    	(
            'status'       => DS_STATUS_DOING,
            'real_end_time <=' => $real_end_time,
    	);
    	print_r($where);


        $this->load->model('direct_seeding/Model_direct_seeding_join_log', 'dsjl');
    	$this->load->model('direct_seeding/Model_direct_seeding', 'ds');
    	$data = $this->ds->getAllLists($where);


        $this->load->service('message/service_message_im');


    	print_r($data);
    	foreach ($data as $v)
    	{
    		if(!$v['chat_room_num'])
    		{
    		    continue;
    		}


            if(strtotime($v['real_end_time']) <= TIMESTAMP)
            {
                $param = array
                (
                    'chat_room_num' => $v['chat_room_num'],
                    'content'       => '@MSMK@LIVING_ALREADY_END@',
                );
                $this->service_message_im->group_send($param);//$param['chat_room_num'], $param['content']);
                //$ret = $api->group_send_group_msg("admin", , "@MSMK@LIVING_ALREADY_END@");
                //print_r($ret);
            }
            else
            {
                $remind_second = (strtotime($v['real_end_time']) - TIMESTAMP);
                $remind_minute = ceil($remind_second / 60);
                $remind_minute = $remind_minute > 5 ? 5 : $remind_minute;
                    //(1 > $remind_minute ) && $remind_minute = 1;


                    $message = array
                    (
                        'remind_second' => $remind_second,
                        'remind_minute' => $remind_minute,
                    );


                    $param = array
                    (
                        'chat_room_num' => $v['chat_room_num'],
                        'content'       => '@MSMK@LIVING_WILL_END@'.$remind_minute,
                    );
                    $this->service_message_im->group_send($param);
                    //$ret = $api->group_send_group_msg("admin", $v['chat_room_num'], "@MSMK@LIVING_WILL_END@".$remind_minute);//json_encode($message));


                    //*
                    if (1 == $remind_minute)
                    {
                        $this->load->service('finance/service_finance_tools');
                        $ds_income = $this->service_finance_tools->ds_income($v['ds_id']);
                    $anchor_income = isset($ds_income['data']['anchor_income']) ? $ds_income['data']['anchor_income'] : 0;
                    $auction_income = isset($ds_income['data']['auction_income']) ? $ds_income['data']['auction_income'] : 0;


                    $count_number = $this->dsjl->watch_number($v['ds_id']);
                    $join_num = $count_number['data']['number'];


                    $item = array
                    (
                        'duration'       => gmstrftime('%H:%M:%S', (strtotime($v['real_end_time'])-strtotime($v['real_start_time']))),
                        'join_num'       => $join_num,
                        'anchor_income'  => $anchor_income,
                        'auction_income' => $auction_income,
                    );
                    $this->service_message_im->modify_group($v['chat_room_num'], array('notification' => json_encode($item)));
                }
                //*/

                //print_r($ret);
            }
    	}
    }
    
    
    /**
     * 直播间提示
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/live_tips_text
     */
    public function live_tips_text()
    {    	
    	$this->load->library('im_api/TimRestApi');
    
    	$api = createRestAPI();
    
    	$ret = $api->generate_user_sig();
    	if ($ret == null)
    	{
    		// 签名生成失败
    		echo '签名生成失败';
    		die();
    	}
    	 
    	$this->load->model('direct_seeding/Model_direct_seeding', 'ds');
    	$data = $this->ds->getAllLists(array('status'=>DS_STATUS_DOING,));
    	 
    	foreach ($data as $v)
    	{
    		if($v['chat_room_num'])
    		{
    			$ret = $api->group_send_group_msg("admin", $v['chat_room_num'], "@MSMK@BROADCAST@".LIVE_TIPS_TEXT);
    			print_r($ret);
    		}
    	}
    }


    /**
     * 直播结束
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/live_end
     */
    public function live_end()
    {
    	$this->load->model('direct_seeding/Model_direct_seeding', 'ds');
    	
    	$lists = $this->ds->getAllLists(array('status'=>DS_STATUS_NOT));
    	foreach($lists as $v)
    	{
    		if(strtotime($v['start_time'])+$v['duration']*60 < TIMESTAMP)
    		{
    			$this->ds->update(array('status'=>DS_STATUS_CONSULT, 'end_type'=>DIRECT_SEEDING_END_PLATFORM), array('ds_id'=>$v['ds_id']));
    		}
    	}
    	
    	$real_end_time = date('Y-m-d H:i:59', strtotime("-3 minutes"));
    	$where = array
    	(
            'status'       => DS_STATUS_DOING,
            'real_end_time <=' => $real_end_time,
    	);
    	print_r($where);
    	$data = $this->ds->getAllLists($where);

		print_r($data);
        $this->load->model('direct_seeding/Model_direct_seeding_join_log', 'dsjl');


    	foreach ($data as $v)
    	{
    	    //判断主播是否开播过，如果未开播过，则直播更新为等待退款
    	    $where = array
            (
                'ds_id' => $v['ds_id'],
                'uid' => $v['anchor_uid'],
            );
    	    $join_log_item = $this->dsjl->getOne($where);


            $item['end_type'] = DIRECT_SEEDING_END_PLATFORM;
    	    $item['status']   = empty($join_log_item) ? DS_STATUS_CONSULT : DS_STATUS_ABNORMAL;


    		$this->ds->save($item, $v['ds_id']);
    		
    		//print_r($v);
    		
    		if($v['chat_room_num'])
    		{
                $count_number = $this->dsjl->watch_number($v['ds_id']);
                $join_num = $count_number['data']['number'];

    			
    			$duration = time()-strtotime($v['real_start_time']);
    			$duration = $duration>0 ? $duration:0;
    			
    			$direct_seeding_end['duration']   = gmstrftime('%H:%M:%S', $duration);
    			$direct_seeding_end['join_num']   = $join_num;

                $this->load->service('finance/service_finance_tools');
                $ds_income = $this->service_finance_tools->ds_income($v['ds_id']);
                $anchor_income = isset($ds_income['data']['anchor_income']) ? $ds_income['data']['anchor_income'] : 0;
                $auction_income = isset($ds_income['data']['auction_income']) ? $ds_income['data']['auction_income'] : 0;


    			$this->load->service('message/service_message_im');
    			$data = array(
    					'chat_room_num' => $v['chat_room_num'],
    					'content' => '@MSMK@GROUP_CHAT_ROOM_DELETE@'.$direct_seeding_end['duration'].'aa668888866aa'.$direct_seeding_end['join_num'].'aa668888866aa'.$anchor_income.'aa668888866aa'.$auction_income,
    			);
    			$send_rs = $this->service_message_im->group_send($data);
    			
    			//print_r($send_rs);
    		}
    	}
    }


    /**
     * 个人综合评分
     *
     * php /data/www/shikee/web/cli.php direct_seeding/Base/comprehensive_score
     */
    public function comprehensive_score()
    {
        $this->load->model('direct_seeding/Model_direct_seeding', 'ds');
        $where = array('score >' => 0);
        $data  = $this->ds->getAllLists($where, true, false, 'anchor_uid, AVG(score) as score, ds_id', 'anchor_uid');


        $this->load->model('user/Model_user', 'u');
        foreach ($data as $v)
        {
            $item = array
            (
                'score' => '5.0',//$v['score']
            );


            $this->u->update($item, array('uid'=>$v['anchor_uid']));
        }
    }
}